import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { prisma } from '@/lib/prisma';
import { auth } from '@/lib/auth';

const handler = NextAuth({
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: '用户名', type: 'text' },
        password: { label: '密码', type: 'password' }
      },
      async authorize(credentials) {
        if (!credentials?.username || !credentials?.password) {
          return null;
        }

        try {
          // 首先尝试使用默认管理员账户（用于初始设置）
          if (credentials.username === 'admin' && credentials.password === 'admin123') {
            return {
              id: 'admin',
              name: 'Administrator',
              email: 'admin@example.com',
              role: 'admin'
            };
          }

          // 从数据库中查询管理员账户
          const admin = await prisma.admin.findUnique({
            where: { username: credentials.username },
          });
          
          if (!admin) {
            return null;
          }

          // 验证密码
          const passwordMatch = admin.salt && admin.hash
            ? auth.verifyPassword(credentials.password, admin.hash, admin.salt)
            : false;
          
          if (!passwordMatch) {
            return null;
          }

          // 返回管理员信息
          return {
            id: admin.id.toString(),
            name: admin.username,
            email: admin.email || 'admin@example.com',
            role: admin.role
          };
        } catch (error) {
          console.error('认证错误:', error);
          return null;
        }
      },
    }),
  ],
  pages: {
    signIn: '/login',
    error: '/login',
  },
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30天
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      if (session.user) {
        session.user.role = token.role;
      }
      return session;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
});

export { handler as GET, handler as POST };